package com.xy.job.executor.log

import com.xy.job.executor.log.factory.*
import com.xy.job.executor.log.logger.Logger
import java.util.concurrent.ConcurrentHashMap
import kotlin.reflect.KClass

object LoggerFactory {

    private var loggerFactory: ILoggerFactory = NopLoggerFactory()

    private val loggerCache: MutableMap<String, Logger> = ConcurrentHashMap()

    init {
        val loggerFactoryInitMethods = arrayOf(
            { loggerFactory = LogbackLoggerFactory() },
            { loggerFactory = Log4j2LoggerFactory() },
            { loggerFactory = Log4jLoggerFactory() },
        )
        loggerFactoryInitMethods.map { runCatching { it.invoke() } }
            .firstOrNull() { it.isSuccess }

        if (loggerFactory !is NopLoggerFactory) {
            println("init logger with ${loggerFactory.javaClass.simpleName} success")
        } else {
            println("init logger with NopLoggerFactory, pay attention.")
        }
    }

    @JvmStatic
    fun getLogger(name: String): Logger {
        return loggerCache.computeIfAbsent(name) {
            loggerFactory.getLogger(name)
        }
    }

    @JvmStatic
    fun getLogger(clazz: Class<*>): Logger {
        return getLogger(clazz.getName())
    }

    @JvmStatic
    fun getLogger(clazz: KClass<*>): Logger {
        return getLogger(clazz.qualifiedName!!)
    }
}